﻿// <copyright file="DateTimeConverter.cs" company="Microsoft Corporation">
// Copyright (c) 2008 All Right Reserved
// </copyright>
// <author>Michael S. Scherotter</author>
// <email>mischero@microsoft.com</email>
// <date>2009-03-06</date>
// <summary>DateTime converter</summary>

namespace NYTimes.ValueConverters
{
    using System;
    using System.Windows.Data;

    /// <summary>
    /// DateTime Converter for Data binding
    /// </summary>
    public class DateTimeConverter : IValueConverter
    {
        #region IValueConverter Members

        /// <summary>
        /// Converts from a DateTime to a string using the parameter as a formatting parameter.
        /// </summary>
        /// <param name="value">The source data being passed to the target </param>
        /// <param name="targetType">The Type of data expected by the target dependency property.</param>
        /// <param name="parameter">An optional parameter to be used in the converter logic.</param>
        /// <param name="culture">The culture of the conversion.</param>
        /// <returns>The value to be passed to the target dependency property. </returns>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is DateTime)
            {
                var dt = (DateTime)value;

                if (parameter == null)
                {
                    return dt.ToString(culture);
                }
                else
                {
                    return dt.ToString(parameter as string, culture);
                }
            }

            return null;
        }

        /// <summary>
        /// Converts from a string to a DateTime object.
        /// </summary>
        /// <param name="value">The target data being passed to the source.</param>
        /// <param name="targetType">The Type of data expected by the source object.</param>
        /// <param name="parameter">An optional parameter to be used in the converter logic. </param>
        /// <param name="culture">The culture of the conversion.</param>
        /// <returns>The value to be passed to the source object.</returns>
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var strValue = value as string;

            if (strValue != null)
            {
                return DateTime.Parse(strValue, culture);
            }

            return null;
        }

        #endregion
    }
}
